import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.net.*; public class ServletsSiteReader extends HttpServlet { // stores the parameter names and values. String fileName = "/Tomcat4/webapps/ROOT/WEB-INF/classes/temp.txt"; //private File file = new File( fileName ); // stores the text from site assigned as parameter private StringBuffer buf; public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); final PrintWriter out = res.getWriter(); out.print( "
" );
out.print( "File IO From a Servlet" ); out.print( "" ); // store the parameter values in enumParam. Enumeration enumParam = req.getParameterNames(); // only one parameter String paramName = ""; String paramValue[] = { "","","","" }; while( enumParam.hasMoreElements() ) { // Returns the next element of this enumeration if this enumeration object has // at least one more element to provide. paramName = (String) enumParam.nextElement(); // Returns the value of a request parameter as a String, or null if the parameter // does not exist. Request parameters are extra information sent with the request. // For HTTP servlets, parameters are contained in the query string or posted form data. paramValue = req.getParameterValues( paramName ); } // store the site name to the output file try { RandomAccessFile file = new RandomAccessFile( "/Tomcat4/webapps/ROOT/WEB-INF/classes/temp.txt","rw" ); //PrintWriter outFile = new PrintWriter( new FileWriter( file ) ); file.seek( file.length() ); file.writeBytes( paramName+" "+paramValue[0]+'\n' ); //outFile.println( paramName+" "+paramValue[0] ); //outFile.close(); file.close(); } catch ( FileNotFoundException e ) { // If this file does not exist out.print( " File not found. (temp.txt) " ); } catch ( IOException e ) { out.print( "An IO exception encountered!" ); } // Now, read the contents of the file back to the page as HTML content. // read the site name from the output file to the HTML page/ try { // Create a buffered reader to read each line from a file. BufferedReader in = new BufferedReader( new FileReader( fileName ) ); String s; // Read each line from the file and echo it to the screen. s = in.readLine(); out.print( "" );
while ( s != null )
{
out.print( s+"" );
// Close the buffered reader, which also closes the file reader.
in.close();
}
catch ( FileNotFoundException e )
{
// If this file does not exist
out.print( "File not found. (temp.txt) " ); } catch ( IOException e ) { out.print( "Got an IO exception, dude!" ); } out.print( " |